const sqlite3 = require('sqlite3').verbose();
const path = require('path');

// 连接到数据库
const dbPath = path.join(__dirname, '../resources/db/db.database');
const db = new sqlite3.Database(dbPath);

console.log('=== 检查当前user_lesson_progress表中的time_spent字段 ===');

// 查询当前的进度数据
db.all('SELECT * FROM user_lesson_progress', (err, rows) => {
  if (err) {
    console.error('查询出错:', err);
    db.close();
    return;
  }
  
  console.log('当前进度数据:');
  rows.forEach(row => {
    console.log(`ID: ${row.id}, 用户ID: ${row.user_id}, 课时ID: ${row.lesson_id}, 课程ID: ${row.course_id}, 完成度: ${row.completion_percentage}%, 是否完成: ${row.is_completed}, 学习时长: ${row.time_spent}秒`);
  });
  
  // 选择一条记录来测试更新
  if (rows.length > 0) {
    const testRow = rows[0];
    const newTimeSpent = testRow.time_spent + 60; // 增加60秒
    
    console.log(`\n=== 更新用户ID ${testRow.user_id}, 课时ID ${testRow.lesson_id} 的学习时长 ===`);
    console.log(`原学习时长: ${testRow.time_spent}秒, 新学习时长: ${newTimeSpent}秒`);
    
    // 模拟调用updateLessonProgress函数的效果
    const updateQuery = `
      UPDATE user_lesson_progress 
      SET time_spent = ?, completion_percentage = ?, is_completed = ?, updated_at = CURRENT_TIMESTAMP
      WHERE user_id = ? AND lesson_id = ?
    `;
    
    db.run(updateQuery, [newTimeSpent, testRow.completion_percentage, testRow.is_completed, testRow.user_id, testRow.lesson_id], function(err) {
      if (err) {
        console.error('更新出错:', err);
        db.close();
        return;
      }
      
      console.log(`成功更新 ${this.changes} 条记录`);
      
      // 再次查询验证更新结果
      db.get('SELECT * FROM user_lesson_progress WHERE user_id = ? AND lesson_id = ?', [testRow.user_id, testRow.lesson_id], (err, updatedRow) => {
        if (err) {
          console.error('查询更新结果出错:', err);
        } else {
          console.log(`\n更新后的数据:`);
          console.log(`ID: ${updatedRow.id}, 用户ID: ${updatedRow.user_id}, 课时ID: ${updatedRow.lesson_id}, 课程ID: ${updatedRow.course_id}, 完成度: ${updatedRow.completion_percentage}%, 是否完成: ${updatedRow.is_completed}, 学习时长: ${updatedRow.time_spent}秒`);
        }
        
        db.close();
      });
    });
  } else {
    console.log('没有找到进度数据');
    db.close();
  }
});